package pcache

import (
	"sync"

	"gitee.com/linxing_3/sr-core/config"
	"gitee.com/linxing_3/sr-core/plugins/storage/cache"
	"gitee.com/linxing_3/sr-core/relay"
	"gitee.com/linxing_3/sr-core/yerr"
	"gitee.com/mkwchecking/sr-admin/pkg/instance"
)

type YCacheKey struct{}

var cacheLock = &sync.Mutex{}

func UpsertCache() (cache.ICache, error) {
	cacheLock.Lock()
	defer cacheLock.Unlock()

	cache, err := instance.GetOrInit(YCacheKey{}, initCache)
	if err != nil {
		return nil, err
	}

	return *cache, nil
}

func initCache() (cache.ICache, error) {
	if cache, ok := cache.FromCtx(relay.Context()); ok {
		return cache, nil
	}

	cacheSet, err := cache.Install(config.Get().Cache)
	if err != nil {
		return nil, err
	}

	cache, ok := cacheSet.GetDefault()
	if !ok {
		return nil, yerr.ErrBizPluginNotFound.Error("cache")
	}

	return cache, nil
}
